import java.util.Arrays;

/**
 * Created by zhourh on 2018/9/19.
 *
 * 给定一个长度为 n 的非空整数数组，找到让数组所有元素相等的最小移动次数。每次移动可以使 n - 1 个元素增加 1。

 示例:

 输入:
 [1,2,3]

 输出:
 3

 解释:
 只需要3次移动（注意每次移动会增加两个元素的值）：

 [1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

 */
public class MinimumMovesToEqualArrayElements {


    public static void main(String[] args) {
        System.out.println(new MinimumMovesToEqualArrayElements().minMoves(new int[]{1,1,2,3}));
        System.out.println(new MinimumMovesToEqualArrayElements().minMoves(new int[]{1,2147483647}));
        System.out.println(new MinimumMovesToEqualArrayElements().minMoves(new int[]{1,1,2147483647}));
        System.out.println(new MinimumMovesToEqualArrayElements().minMoves(new int[]{-100, 0, 100}));
    }

    public int minMoves(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return 0;
        }

        long n = nums.length;
        long min = min(nums);
        int move = 0;
        for (int i = 0; i < n; i++) {
            move += nums[i] - min;
        }

       return move;

    }

    private int min(int[] nums) {
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            if (min > nums[i]) {
                min = nums[i];
            }
        }

        return min;
    }
}
